import type { CardQueryParams } from '/@/api/general/model/cardModel';
import type { SeriesItem } from '/@/api/general/model/seriesModel';
import { defineComponent, ref, toRaw, unref } from 'vue';
import { useVModels } from '@vueuse/core';
import { useSeriesOptions } from '/@/views/general/hooks/useSeries';
import { cloneDeep, debounce, filter, includes, indexOf } from 'lodash-es';
import setting from '/@/settings/projectSetting';
import { ConfigProvider, Empty, Popup, Search } from 'vant';

import('./SeriesSearchPopup.less');

export default defineComponent({
  name: 'SeriesSearchPopup',
  props: {
    show: {
      type: Boolean as PropType<boolean>,
      required: true,
      default: () => {
        return false;
      },
    },
    queryState: {
      type: Object as PropType<CardQueryParams>,
      required: true,
    },
    gameId: {
      type: String as PropType<string>,
      required: true,
    },
  },
  emits: ['update:show', 'pageRefresh'],
  setup(props, { emit }) {
    const { show } = useVModels(props, emit);

    const { yearSeriesData, seriesData, handleSeriesDate, seriesGetData } = useSeriesOptions();
    seriesGetData({ game_id: props.gameId });

    const activeYearIndex = ref(0);
    const activeYearClick = (index: number) => {
      activeYearIndex.value = index;
    };
    const activeSeriesItemClick = (item: SeriesItem) => {
      const { queryState } = props;
      const selectValue = item.series_id;
      if (includes(queryState.series_ids, String(selectValue))) {
        const index = indexOf(queryState.series_ids, String(selectValue));
        queryState.series_ids?.splice(index, 1);
      } else {
        queryState.series_ids?.push(String(selectValue));
      }
      emit('pageRefresh');
    };

    // 系列搜索
    const searchState = ref('');
    const searchClick = debounce((val: string) => {
      console.log(val);
      const cloneData = cloneDeep(toRaw(seriesData));
      const newData = filter(cloneData, (item) => {
        return item.name.indexOf(val) >= 0;
      });
      handleSeriesDate(newData);
    }, 500);

    return () => (
      <Popup
        class='search-series-popup'
        v-model={[show.value, 'show']}
        style={{ width: '82%', height: '76%', top: '58%', background: '#F9F9F9', zIndex: setting.PageTitleZIndex - 1 }}
        overlayStyle={{ zIndex: setting.PageTitleZIndex - 1 }}
        closeable={true}
      >
        <ConfigProvider themeVars={{ searchContentBackground: '#E6E6E6' }}>
          <Search
            background={'#F9F9F9'}
            placeholder={'搜索'}
            clearable={true}
            shape={'round'}
            v-model={[searchState.value]}
            onUpdate:modelValue={searchClick}
          />
        </ConfigProvider>
        {yearSeriesData.length ? (
          <div class={'series-box'}>
            <ul class={'series-year-box'}>
              {yearSeriesData.map((item, index) => {
                let classVar = 'series-year-item text-gray-400';
                unref(activeYearIndex) === index ? (classVar += ' text-gray-800 active') : null;
                return (
                  <li
                    class={classVar}
                    onClick={() => {
                      activeYearClick(index);
                    }}
                  >
                    {item.year}年
                  </li>
                );
              })}
            </ul>
            <ul class={'series-list-box'}>
              {yearSeriesData[unref(activeYearIndex)]?.list.map((item) => {
                let classVar = 'series-list-item';
                includes(props.queryState.series_ids, String(item.series_id)) ? (classVar += ' active') : '';
                return (
                  <li
                    class={classVar}
                    onClick={() => {
                      activeSeriesItemClick(item);
                    }}
                  >
                    <h3 class={'text-base leading-none mb-sm'}>{item.name}</h3>
                    <h4 class={'text-sm leading-none text-gray-400'}>{item.ename}</h4>
                  </li>
                );
              })}
            </ul>
          </div>
        ) : (
          <Empty>没有相关系列</Empty>
        )}
      </Popup>
    );
  },
});
